package com.geek.novel.db

import com.geek.novel.common.Constant
import com.geek.novel.entity.BookRead
import com.geek.novel.utils.LogCatUtil
import io.realm.DynamicRealm
import io.realm.FieldAttribute
import io.realm.RealmMigration
import java.util.*


/**
 * Realm升级数据库
 */
class CustomMigration : RealmMigration {
	
	override fun migrate(realm: DynamicRealm, oldV: Long, newV: Long) {
		var oldVersion = oldV
		val newVersion = newV
		val schema = realm.schema
		LogCatUtil.i("", "升级数据库，旧版本：${oldVersion}，新版本：${newVersion}, 配置版本：${Constant.REALM_DB_VERSION_CODE}")
		//根据版本判断并进行升级操作
		var version = 1
		if(version in oldVersion until newVersion){//添加阅读历史记录、书籍全本缓存的数据表
			val bookDownload = schema.create("BookDownload")
			bookDownload?.addField("id", Long::class.java)?.addPrimaryKey("id")
				?.addField("bookId", String::class.java, FieldAttribute.REQUIRED)
				?.addField("bookCrawlerId", Long::class.java, FieldAttribute.REQUIRED)
				?.addField("crawlerIndex", Int::class.java, FieldAttribute.REQUIRED)
				?.addField("status", Int::class.java, FieldAttribute.REQUIRED)
			oldVersion++
		}

		version = 2
		if(version in oldVersion until newVersion){
			val bookRead = schema.get("BookRead")
			bookRead?.addField("endTime", Date::class.java)
					?.removeField("lastCrawlerTime")

			val bookCrawler = schema.get("BookCrawler")
			bookCrawler?.addField("lastCrawlerTime", Date::class.java)

			oldVersion++
		}

		version = 3
		if(version in oldVersion until newVersion){//添加搜索历史记录表
			val searchHistory = schema.create("SearchHistory")
			searchHistory?.addField("id", Long::class.java)?.addPrimaryKey("id")
				?.addField("searchText", String::class.java, FieldAttribute.REQUIRED)
				?.addField("count", Int::class.java, FieldAttribute.REQUIRED)
				?.addField("searchTime", Long::class.java, FieldAttribute.REQUIRED)
			oldVersion++
		}
	}

}